//
//  HD_HSP_AQcode_ViewController.m
//  HDLiaoNingMeseum
//
//  Created by HDHaoShaoPeng on 2017/8/7.
//  Copyright © 2017年 HDNiuKuiming. All rights reserved.
//

#import "HD_HSP_AQcode_ViewController.h"
#import "HD_HSP_Exhibit_Model.h"
#import "HD_HSP_Player_ViewController.h"
#import "HD_LY_DownloadManager.h"
#import <AVFoundation/AVFoundation.h>

@interface HD_HSP_AQcode_ViewController ()
@property (strong, nonatomic)HD_HSP_Exhibit_Model *myResource;

@property (weak, nonatomic) IBOutlet UILabel *myTitleLabel;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property (strong, nonatomic) UIAlertView *alertViewQRCode;
@property (strong,nonatomic) AVCaptureDevice * device;
@property (strong,nonatomic) AVCaptureDeviceInput * input;
@property (strong,nonatomic) AVCaptureMetadataOutput * output;
@property (strong,nonatomic) AVCaptureSession * session;
@property (strong,nonatomic) AVCaptureVideoPreviewLayer * preview;
@property (nonatomic,retain) UIImageView * line;
@property (nonatomic,retain) NSTimer * timer;
@property (nonatomic, strong)HD_LY_DownloadManager *myDownloader;
@end

static HDDeclare *declare;
@implementation HD_HSP_AQcode_ViewController
{
    int num;
    BOOL upOrdown;
}



- (IBAction)backClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    declare = [HDDeclare sharedDeclare];
    self.myTitleLabel.text = declare.QRCodePage;
    self.myTitleLabel.font = [UIFont fontWithName:@"FZQKBYSJW--GB1-0" size:18.0];
//    self.bottomView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:1.0];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resetCamera) name:Downloader_Cancel_Or_Failed_Notification object:nil];
    
    // 判断用户是否授权使用相机
    if (!TARGET_IPHONE_SIMULATOR)
    {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if(status == AVAuthorizationStatusAuthorized) {
            // authorized
            [self permitCamera];
        }
        
        else if(status == AVAuthorizationStatusNotDetermined){
            // not determined
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if(granted){
                    [self permitCamera];
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }}];
        }
        
        else if(status == AVAuthorizationStatusDenied)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:declare.alertTitle message:declare.cameraUnavailable delegate:nil cancelButtonTitle:declare.alertOK otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_timer invalidate];
    self.timer = nil;
}

- (void)permitCamera
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self cameraClean];
        [self setupCamera];
        
        upOrdown = NO;
        num = 0;
        CGFloat originX = (ScreenWidth-300)/2;
        CGFloat originY = 150*ScreenWidth/320;
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(originX, originY-10, 300, 300)];
        imageView.image = [UIImage imageNamed:@"pick_bg"];
        [self.bottomView addSubview:imageView];
        
        //    _line = [[UIImageView alloc] initWithFrame:CGRectMake((self.bottomView.frame.size.width-220)/2, originY, 220, 2)];
        _line = [[UIImageView alloc] initWithFrame:CGRectMake(originX+20, originY, imageView.frame.size.width-40, 2)];
        _line.contentMode = UIViewContentModeScaleToFill;
        _line.image = [UIImage imageNamed:@"QRCode_line"];
        [self.bottomView addSubview:_line];
        
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
        LOG(@"______ Camera Connect______!!!");
    });
}

- (void)setupCamera
{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    if (!TARGET_IPHONE_SIMULATOR)
    {
        _output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    }
    
    // Preview
    CGFloat originX = (ScreenWidth-300)/2+10;
    CGFloat originY = 150*ScreenWidth/320;
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =CGRectMake(originX, originY, 280, 280);
    
    [self.bottomView.layer insertSublayer:self.preview atIndex:0];
    
    // Start
    [_session startRunning];
}

-(void)animation1
{
    //CGFloat width = 220*ScreenWidth/320;
    CGFloat originY = 150*ScreenWidth/320;
    CGFloat originX = _line.frame.origin.x;
    CGFloat width = _line.frame.size.width;
    
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(originX, originY+2*num, width, 2);
        if (2*num == 280) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake(originX, originY+2*num, width, 2);
        if (num == 0) {
            upOrdown = NO;
        }
    }
}


-(void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        [_timer invalidate];
        self.timer = nil;
    }];
}

#pragma mark
#pragma mark -------- AVCaptureMetadata OutputObjects Delegate --------

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    [_session stopRunning];
    [_timer invalidate];
    self.timer = nil;
    
    if ([metadataObjects count] >0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        
        [self pushFromQRCode:[NSString stringWithFormat:@"%@",stringValue]];
        NSLog(@"扫描到的字符串：%@",stringValue);
    }
}

- (void) pushFromQRCode:(NSString *)number
{
    
    NSArray *tempArray = [declare giveMeExhibitData];
    
    for (HD_HSP_Exhibit_Model *model in tempArray) {
        if (model.FileNum.integerValue == number.integerValue) {
            
            UIStoryboard *board = [UIStoryboard storyboardWithName:@"HD_HSP_Data" bundle:nil];
            HD_HSP_Player_ViewController *vc = [board instantiateViewControllerWithIdentifier:@"HD_HSP_Player_ViewController"];
            vc.detailItem = model;
            [self.navigationController pushViewController:vc animated:YES];
            
            
            return;
        }
        
    }
    
    
    
    if (_alertViewQRCode != nil)
    {
        [_alertViewQRCode dismissWithClickedButtonIndex:0 animated:NO];
        self.alertViewQRCode = nil;
    }
    _alertViewQRCode = [[UIAlertView alloc]initWithTitle:declare.alertTitle
                                                 message:declare.InvalidInput
                                                delegate:self
                                       cancelButtonTitle:declare.alertOK
                                       otherButtonTitles:nil, nil];
    _alertViewQRCode.tag = 0x1026;
    [_alertViewQRCode show];
}

- (BOOL)isLegalNumber:(NSString *)number
{
//    if (number.length > 4 || number.integerValue <= 0)
//        return YES;
//    
//    NSString *originalString = number;
//    NSScanner *scanner = [NSScanner scannerWithString:originalString];
//    NSCharacterSet *numbers = [NSCharacterSet
//                               characterSetWithCharactersInString:@"0123456789"];
//    
//    NSString *buffer = nil;
//    while ([scanner isAtEnd] == NO) {
//        if (![scanner scanCharactersFromSet:numbers intoString:&buffer]) {
//            return YES;
//            break;
//        }
//    }
    
    return YES;
}


#pragma mark
#pragma mark -------- Alert　Delegate --------

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self resetCamera];
}

- (void)resetCamera
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [_session startRunning];
        _timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    });
}

- (void)cameraClean
{
    self.device = nil;
    self.input = nil;
    self.output = nil;
    self.session = nil;
    
    [self.preview removeFromSuperlayer];
    self.preview = nil;
    [self.bottomView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
}

- (void)dealloc
{
    [self cameraClean];
    [self.myDownloader cleanDownloder];
    self.myDownloader = nil;
    
    if (_alertViewQRCode != nil)
    {
        [_alertViewQRCode dismissWithClickedButtonIndex:0 animated:NO];
        self.alertViewQRCode = nil;
    }
    self.myResource = nil;
    self.line = nil;
}

@end
